<template>
  <el-dialog
    title="角色授权"
    v-model="rulesDialogVisble"
    width="35%"
    :before-close="closeBox"
  >
    <!-- <div>{{ authForm.rules }}</div> -->
    <div>
      <el-tree
        ref="authTree"
        :data="ruleMenu"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :default-checked-keys="authForm.rules"
        :props="mProps"
      />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeBox">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, watch, computed, reactive, nextTick } from "vue";
import { ElMessage, FormInstance } from "element-plus";

const pors = defineProps({
  showdialog: {
    type: Boolean,
    default: false,
  },
  list: {
    type: Object,
    default: {},
  },
  ruleMenu: {
    type: Array,
    default: [],
  }, //权限菜单数组
});
const authTree = ref(); //定义
const authForm = computed(() => pors.list); //给当前变量赋值
// const authForm = ref(pors.list);
// watch(
//   () => pors.list,
//   (newVal) => {
//     authForm.value = newVal; //值变更时赋值
//   }
// );

const mProps = {
  label: "title",
  // checkStrictly:true, //设置父子节点取消选中关联，从而达到选择任意一级选项的目的
}; //上级权限菜单组件设置

const emits = defineEmits(["useConfirm", "useClose"]); //定义一个或多个自定义按钮事件 传递到父组件

const rulesDialogVisble = ref(false); // 定义控制弹窗显隐的变量

//关闭模态框
const closeBox = () => {
  rulesDialogVisble.value = false; //重置为空
  emits("useClose", rulesDialogVisble.value);
  //防止下次打开还是 当前关闭后的勾选状态 所以关闭前需要清空 勾选状态
  nextTick(() => {
    authTree.value.setCheckedKeys([]); //设置目前选中的节点，使用此方法必须设置 node-key 属性
  });
};

//确定/提交
const submitForm = () => {
  let pid = [],
    me = [];

  pid = authTree.value.getHalfCheckedKeys();//返回目前半选中的节点的 key 所组成的数组 父级和祖父级id  不需要父级因为存储了父级 下面子级未选者都会选中 所以不能存储父级
  me = authTree.value.getCheckedKeys(); //当前选中的节点
  let save = {
    id: pors.list.id,
    rules: me, //选中 或全选 的菜单
    pidRules:pid,//半选中的，一般为上级的菜单
  };
  emits("useConfirm", save);
  //防止下次打开还是 当前关闭后的勾选状态 所以关闭前需要清空 勾选状态
  nextTick(() => {
    authTree.value.setCheckedKeys([]); //设置目前选中的节点，使用此方法必须设置 node-key 属性
  });
  rulesDialogVisble.value = false;
};

// 将变量暴露出来
defineExpose({
  rulesDialogVisble,
});
</script>
